<?php

declare(strict_types=1);

namespace App\Controller\Init;

use App\Controller\BaseController;
use App\Services\Upload\OssService;
use App\Utils\MemcacheClient;
use Hyperf\Context\Context;
use Hyperf\Di\Annotation\Inject;
use function Hyperf\Config\config;

class AliYunController extends BaseController
{

    #[Inject]
    public OssService $ossService;

    /**
     * Note - 获取阿里云oss上传的参数
     * DateTime 2024/8/20 14:42
     * User Admin
     * @return \Psr\Http\Message\ResponseInterface
     */
    public function resource()
    {
        $userinfo = Context::get('user');
        $uid = $userinfo['id'];
        $session_id = $this->request->input('session_id');
        $data['endpoint'] = config('oss.aliyun.endpoint');
        $data['stsServer'] = HOST . "/app/v1/aliyun/upload_tokens.php?uid=" . $uid . "&session_id=" . $session_id;
        $data['bucketName'] = config('oss.aliyun.bucket');
        $data['imghost'] = config('oss.aliyun.img_domain');
        return $this->return(formatData(['result' => 1, 'msg' => $data]));
    }

    /**
     * Note - 获取阿里云oss临时凭证
     * DateTime 2024/8/20 15:19
     * User Admin
     * @return \Psr\Http\Message\ResponseInterface|string
     */
    public function uploadTokens()
    {
        $uploadInfo = MemcacheClient::getInstance()->get("aliyun_upload_info");
        if (empty($uploadInfo)) {
            $uploadInfo = $this->ossService->assumeRole();
            if (!empty($uploadInfo)) {
                MemcacheClient::getInstance()->set("aliyun_upload_info", $uploadInfo, 3500);
            }
        }
        return json_encode($uploadInfo);
        // return $this->response->json($uploadInfo);
        // return $this->return(formatData(['result' => 1, 'msg' => $uploadInfo]));
    }
}
